package com.gwc.schedule.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gwc.schedule.common.Result;
import com.gwc.schedule.common.ResultCodeEnum;
import com.gwc.schedule.pojo.SysUser;
import com.gwc.schedule.service.SysUserService;
import com.gwc.schedule.service.impl.SysUserServiceImpl;
import com.gwc.schedule.util.MD5Util;
import com.gwc.schedule.util.WebUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(
        urlPatterns = {"/user/*"}
)
public class SysUserController extends BaseController{
    private SysUserService sysUser = new SysUserServiceImpl();
    public void add(HttpServletRequest req, HttpServletResponse resq){
        System.out.println("add user");
    }


    /**
     * 用户注册接口
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        // 获取注册的userName和password
//        String username = req.getParameter("username");
//        String userPwd = req.getParameter("userPwd");
//        // 向数据库存储对象
//        SysUser user = new SysUser(null,username, userPwd);
//        int resultRegist = sysUser.regist(user);
//        // 根据返回结果，来返回页面
//        if (resultRegist == 0){
//            resp.sendRedirect("/registFail.html");
//        }else {
//            resp.sendRedirect("/registSuccess.html");
//        }

        // 前后端分离，前端发送一个json字符串信息
        SysUser registerUser =  WebUtil.readJson(req, SysUser.class);
        int resultRegist = sysUser.regist(registerUser);
        Result result = Result.ok(null);
        if (resultRegist<1){
            // 并发情况下，两个人同时注册一个用户名，前端可能校验通过，后端会报错
            result = Result.build(null,ResultCodeEnum.USERNAME_USED);
        }
        WebUtil.writeJson(resp, result);

    }

    /**
     * 用户登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        // 获取注册的userName和password
//        String username = req.getParameter("username");
//        String userPwd = req.getParameter("userPwd");
//        // 从数据库中进行验证
//        SysUser loginUser = sysUser.findByUsername(username);
//        if (loginUser == null){
//            // 用户名错误
//            resp.sendRedirect("/loginUsernameError.html");
//        }else if (! MD5Util.encrypt(userPwd).equals(loginUser.getUserPwd())){
//            // 密码错误
//            resp.sendRedirect("/loginUserPwdError.html");
//        }else {
//            // 登录成功,将用户信息存入session中
//            req.getSession().setAttribute("sysUser", loginUser);
//            resp.sendRedirect("/showSchedule.html");
//        }

        // 前后端分离
        SysUser requestUser = WebUtil.readJson(req, SysUser.class);
        // 从数据库中进行验证
        SysUser loginUser = sysUser.findByUsername(requestUser.getUsername());
        Result result = Result.ok(null);
        if (null == loginUser){
            result = Result.build(null,ResultCodeEnum.USERNAME_ERROR);
        }else if (! MD5Util.encrypt(requestUser.getUserPwd()).equals(loginUser.getUserPwd())){
            result = Result.build(null,ResultCodeEnum.PASSWORD_ERROR);
        }else{
            // 验证通过，返回登录用户的信息,并隐藏用户密码
            loginUser.setUserPwd("");
            Map data = new HashMap();
            data.put("loginUser",loginUser);
            result.setData(data);
        }

        WebUtil.writeJson(resp,result);

    }

    /**
     * 检查数据库中是否存在该用户
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void checkUsernameUsed(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        // 获取用户名
        String username = req.getParameter("username");
//        System.out.println("进入到checkUsernameUsed:"+username);
        // 从数据库中获取相关信息
        SysUser checkUser = sysUser.findByUsername(username);
//        String info = "未注册";
        Result<Object> result = Result.ok(null);
        if (checkUser != null){
//            info = "已注册";
            result = Result.build(null,ResultCodeEnum.USERNAME_USED);
        }
        // 将result作为JSON串返回给客户端
        // 使用第三包里的ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        String info = objectMapper.writeValueAsString(result);

        // 防止编码错误,告诉客户端，返回的是一个JSON
        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(info);
    }
}
